<?php
namespace control;
/*
*工作日类
*/

class workDayClass extends adIndexClass
{
    private const table = 'work_day';
    private const page = 'workDay';
    private const title = '工作日';
    public array $weekOption = ['1'=>'星期一', '2'=>'星期二 ', '3'=>'星期三', '4'=>'星期四', '5'=>'星期五', '6'=>'星期六', '0'=>'星期天'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('clock.table.nian_fen') =>
                        text(array("name" => "startDay", "laydate" => array("type" => "year"), "title" => L('clock.table.nian_fen_qi'))) . "\n-\n" .
                        text(array("name" => "endDay", "laydate" => array("type" => "year"), "title" => L('clock.table.nian_fen_zhi')))
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*查询*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = '';
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        if ($this->power(self::page, "edit")) {
            $button .= "
		<span class='spanButton' onclick=\"layer('".self::page."','edit')\">" . L('clock.table.newWorkDay') . "</span>";
        }
        if ($this->power(self::page, "del")) {
            //控件
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('clock.table.shan_chu') . "</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'      => [
                        'name'  => L('clock.table.gzrmc'),
                        'width' => 300,
                    ],
                    'year' => [
                        'name'  => L('clock.table.nian_fen'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'workDayNum'  => [
                        'name'  => L('clock.table.tian_shu'),
                        'width' => 300,
                    ],
                    'text'         => [
                        'name'  => L('clock.table.bei_zhu'),
                        'width' => 300,
                    ],
                    'updateTime'          => [
                        'name'  => L('clock.table.gxsj'),
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*行政人事-工作日~列表页*/
    public function homeSearch()
    {
        //设置查询变量为空
        $where = "";
        if (!empty($this->post('startDay'))) {
            $where .= " and year >= '" . $this->post('startDay') . "' ";
        }
        if (!empty($this->post('endDay'))) {
            $where .= " and year <= '" . $this->post('endDay') . "' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'year desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $page = $this->page(array("table" => "work_day", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "workDayId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        $workDayNumAll = 0;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = $this->dominate(array(
                "box" => array("name" => "workDayId", "value" => $array['id']),
                "detail" => array("title" => L('clock.table.gzrxq'), "click" => "newIframe('" . L('clock.table.gzrxq') . "','" . root . "control/adIndex.html?cla=workDay&fun=detail&id=" . $array['id'] . "')"),
            ));
            $liButton[] = $dominate;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "workDayNum":
                        $workDayNum = $array['workDay'] ? count(json_decode($array['workDay'], true)) : 0;
                        $workDayNumAll += $workDayNum;
                        $row[] = $workDayNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $button = '';
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('clock.table.gzrmc') . "：" => text(array('name' => 'name', 'class' => 'text', 'value' => $info['name'])),
                    must . L('clock.table.nian_fen') . "：" => text(array('name' => 'year', 'class' => 'text', 'laydate' => ['type' => 'year'], 'value' => $info['year'])),
                ],
                [
                    L('clock.table.bei_zhu') . "：" => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $info['text'])),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 250, "html" => $html));
    }

    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "name" => $this->post('name'),
            "year" => $this->post('year'),
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $workDay = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power("workDay", "edit")) {
            $json['warn'] = L('clock.table.zxbz');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('clock.table.qsrgzrmc');
        } elseif (empty($field['year'])) {
            $json['warn'] = L('clock.table.qsrnf');
        } elseif (sqlNum(self::table, " year = '$field[year]' and name = '$field[name]' and id != '" . $id . "' ") > 0) {
            $json['warn'] = L('clock.table.yczcnfdgzrmc');
        } elseif (empty($workDay['id'])) {
            $userNo = codeTemplateClass::generateCode(self::page, [
                'prefix' => 'WD',
                'table' => self::table,
                'field' => 'orderNo',
                'where' => '',
            ], $field);
            $field = array_merge($field, array("id" => $id, 'orderNo' => $userNo, 'stid' => $this->control['stid'], "time" => date("Y-m-d H:i:s")));
            $json['warn'] = insert(array("table" => self::table, "field" => $field));
        } else {
            $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$workDay[id]'"));
        }
        if (in_array($json['warn'], array('更新成功', '新增成功'))) {
            if ($json['warn'] == '新增成功') {
                //添加当前年份所有非周末的日期
                $this->insertDay($field['year'], $this->post('id'));
            }
            //添加日志
            $text = str_replace(['{{staffName}}', '{{name}}', '{{year}}', '{{id}}'], [$this->control['name'], $field['name'], $field['year'], $id], L('clock.table.workDay_edit_text'));
            $this->logText(array("type" => "workDay", "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=workDay&fun=detail&id=" . $id;
        return json_encode($json, 320);
    }

    public function detailEdit()
    {
        $id = $this->post('id');
        //赋值
        $field = array(
            "workDay" => $_POST['workDay'],//工作日
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $workDay = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('clock.table.nhmzbjzx');
        } elseif (empty($workDay['id'])) {
            $json['warn'] = L('clock.table.wzdcgzr');
        } else {
            $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$workDay[id]'"));
        }
        if (in_array($json['warn'], array('更新成功', '新增成功'))) {
            //添加日志
            $text = str_replace(['{{staffName}}', '{{name}}', '{{year}}', '{{id}}'], [$this->control['name'], $workDay['name'], $workDay['year'], $id], L('clock.table.workDay_edit_text'));
            $this->logText(array("type" => "workDay", "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=workDay&fun=detail&id=" . $id;
        return json_encode($json, 320);
    }

    /*行政人事-工作日~编辑页*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = L('clock.table.no_work_day');
        } else {
            $workDay = query("work_day", " id = '" . $this->get('id') . "' ");
            if (empty($workDay['id'])) {
                $html = L('clock.table.wzdcjl');
            } else {
                $data = array("id" => $workDay['id']);
                $button = [];
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => L('clock.table.shan_chu'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $workDay['id']],
                    ];
                    //按钮
                    $button[] = [
                        "name" => L('clock.table.bian_ji'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "edit",
                        "post" => ["id" => $workDay['id']],
                    ];
                    $button[] = [
                        "name" => L('clock.table.bao_cun'),
                        "type" => '点击事件',
                        "cla" => $this->get('cla'),
                        "fun" => "commitData()",
                        "post" => ["id" => $this->get('id')],
                        'style' => 'li-btn-blue-bg',
                    ];
                }


                $tempHtml = $this->appHtml($workDay['id']);


                $workDayAllLi = "
                 <style>
            [v-cloak] {
                            display: none !important;
                        }
</style>
              <div id=\"app\" v-cloak>
                 {$tempHtml}
            </div>";

                $data['button'] = $this->tableShowButton($button);
                $data['html'] = $this->tableShow(array(
                    "基本信息" => array(
                        array(
                            L('clock.table.gzrbh') => $workDay['orderNo'],
                            L('clock.table.gzrmc') => $workDay['name'],
                            L('clock.table.nian_fen') => $workDay['year'],
                        ),
                        array(
                            L('clock.table.chuang_jian_ren') => self::findStaff($workDay['stid']),
                            L('clock.table.cjsj') => $workDay['time'],
                            L('clock.table.gxsj') => $workDay['updateTime'],
                        ),
                        array(
                            L('clock.table.bei_zhu') => pre($workDay['text']),
                        ),
                    ),
                ));
                $data['html'] .= $this->detailList([
                    'title' => L('clock.table.xzgzr')."<span class='smallButton' onclick=\"layer('" .$this->get('cla') . "','setWorkDay',{'id':'".$workDay['id']."'})\">快捷设置</span>",
                    'html' => "<form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $workDay['id'])) . "<ul class='square'>" . $workDayAllLi . "</ul></form>"
                ]);
                $data['html'] .= "
                    <link type=\"text/css\" href=\"" . root . "static/stylesheet/calendar.css?v=" . version . "\" rel=\"stylesheet\" />
                    <script src=\"" . root . "static/javascript/vue.min.js?v=" . version . "\"></script>
                    <script src='" . root . "static/javascript/calendar.umd.js?v=" . version . "'></script>
                    <script>
                        // 重置data的数据
                        function setWorkDay(res) {
                              $('#app').html(res.html)
                              $('#workDaySetWorkDay').hide()
                        }
                          function commitData() {
                               var formData = new FormData($(\"[name='detailForm']\")[0]);
                                formData.append('workDay', JSON.stringify(window.app.date));
                                //异步提交数据
                                $.ajax({
                                    url: root+'control/adIndex.html?cla=workDay&fun=detailEdit',
                                    type: 'POST',
                                    cache: false,
                                    data: formData,
                                    // 告诉jQuery不要去处理发送的数据
                                    processData: false,
                                    // 告诉jQuery不要去设置Content-Type请求头
                                    contentType: false,
                                    // beforeSend: function () {
                                    //     console.log(\"正在进行，请稍候\");
                                    // },
                                    success: function (res) {
                                        var data = JSON.parse(res);
                                        if (data.warn === 2) {
                                            if (data.href) {//如果异步返回的json参数中定义了重定向url，则跳转到本url
                                                window.location.href = data.href;
                                            } else {
                                                window.location.reload();
                                            }
                                        } else {
                                            warn(data.warn);
                                        }
                                    },
                                    error: function (responseStr) {
                                        console.log(responseStr);
                                    }
                                });
                          }
                    </script>
                   <style>
                    .calendar-pro__body table td .day-box{
                        height: 15px;
                    }
                     .calendar-pro__body table td{
                        text-align: center !important;
                        padding: 0 !important;
                        border: 1px solid #bcdbff;
                     }
                     .calendar-pro__body table th{
                        text-align: center !important;
                        padding: 3px !important;
                     }
                     .calendar-pro__body .select{
                       border-radius:0;
                     }
                        /*****工作日**/
                     .calendar-pro__body table td .day-box.select{
                         background-color: #bcdbff;
                     }
                        /*****在当月中显示的下个月的日期**/
                     .calendar-pro__body table td .day-box.other-month-day{
                       background-color: rgb(239, 239, 239);
                       opacity: 0.1;
                     }
                       /*****在当月中显示的下个月的日期**/
                     .calendar-pro__body table td .day-box.other-month-day .info-date{
                       color: black;
                     }
                     .calendar-pro__body table td .info-date{
                       font-size: 14px;
                     }
                     /*****周末**/
                     .calendar-pro__body table td .day-box.today{
                       outline: none !important;
                     }
                     #app ul li{
                         display:inline-block;
                         padding: 5px 8px;
                     }
                     .calendarD{
                       width: 400px !important;
                       height: 250px;
                     }
                     .dateTitle{
                         width: 100%;
                         text-align: center;
                         padding: 10px 0;
                         font-size: 19px;
                     }
                    </style>
            ";
                $html = $this->tab($data);
            }
        }
        return $html;
    }

    /**
     * 快捷设置
     * @return string
     */
    public function appHtml($id, $week='')
    {
        $tempHtml = '<ul>';
        for ($i = 0; $i < 12; $i++) {
            $tempHtml .= "<li>
                                  <div class='dateTitle'>{{dateTitle[$i]}}</div>
                                  <calendar class='calendarD' multiple :select-date=\"date\" :show-title='false' :default-date='nowDate[$i]' :show-term='false' :show-festival='false' :show-lunar='false'></calendar>
                                  </li>
                                ";
        }
        $tempHtml .= "</ul>
                    <script>
                      $(function() {
                            $.post(root+'control/adIndex.html?cla=workDay&fun=getDay',{id:'$id', week:'$week'},function(res) {
                             window.app = new Vue({
                                el: '#app',
                                data: {
                                    date: res.data.showDate,
                                    nowDate:res.data.nowDate,
                                    dateTitle:res.data.dateTitle
                                }
                              })
                            },'json');
                      })
                    </script>
            ";
        return $tempHtml;
    }

    /**
     * 快捷设置
     * @return string
     */
    public function setWorkDay()
    {
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must. "固定上班日：" => selectMultiple(array("name" => "week[]", "multiple" => true, 'option' => $this->weekOption)),
                ],
            ],
        ]);
        $button = "<input onclick=\"subForm('workDaySetWorkDayForm','" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=" . $this->get('fun') . "Edit" . "',setWorkDay)\" type='button' class='button' value='" . L('button.ConfirmSubmit') . "'>";
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 200, "width" => 600, "html" => $html, "button" => $button));
    }

    public function setWorkDayEdit()
    {
        $id = $this->post('id');
        $week = $this->post('week')?:[];
        $json['warn'] = 2;
        $json['html'] = $this->appHtml($id,implode(',',$week));
        return json_encode($json, 320);
    }

    public function getDay()
    {
        $id = $this->post('id');
        $week = $this->post('week');
        $info = query(self::table, " id = '$id'");
        if($week !== ''){
            $week = explode(',',$week);
            $json['data']['showDate'] = [];
            //获取选中的日期
            $enWeek = [
                'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
            ];
            foreach ($week as $w){
                // 找到今年的第一个星期一
                $firstWeekDay = strtotime("first {$enWeek[$w]} of January {$info['year']}");
                $json['data']['showDate'][] = date('Y-m-d', $firstWeekDay);
                // 循环遍历直到年末
                while (date('Y', $firstWeekDay) == $info['year']) {
                    // 下一个星期一
                    $firstWeekDay = strtotime('+1 week', $firstWeekDay);
                    // 将其添加到数组中
                    $json['data']['showDate'][] = date('Y-m-d', $firstWeekDay);
                }
            }
        }else{
            $json['data']['showDate'] = $info['workDay'] ? json_decode($info['workDay'], true) : [];
        }
        $monthArr = $titleArr = [];
        for ($i = 1; $i <= 12; $i++) {
            $monthArr[] = $info['year'] . '/' . sprintf("%02d", $i);
            $titleArr[] = $i . '月';
        }

        $json['data']['nowDate'] = $monthArr;
        $json['data']['dateTitle'] = $titleArr;
        return json_encode($json, 320);
    }

    /**
     * 添加当前年份所有非周末的日期
     */
    public function insertDay($year, $id)
    {
        $days = [];
        $restDays = [];
        $yumuSecretKey = para('yumuSecretKey');
        $yumuSecretId = para('yumuSecretId');
        $yumuApiHost = para('yumuApiHost');
        $params = [
            'year' => $year,
            'timestamp' => time(),
            'sign' => 1,
            'secretId' => $yumuSecretId,
        ];
        ksort($params); //按照key升序排列
        $strTemp = '';
        foreach ($params as $key => $item) {
            $strTemp .= $key . '=' . $item . '&'; //整合新的参数数组
        }
        $signTemp = $strTemp . "secretKey=" . $yumuSecretKey; //拼接secret
        $signature = md5($signTemp);

        $result = self::curlGet($yumuApiHost . "/interface/v1/index?cla=holidayApp&fun=holidayDate&year=$year&sign=1&timestamp=" . $params['timestamp'] . "&secretId=$yumuSecretId&signature=" . $signature, [], 60);
        if ($result) {
            $res = json_decode($result, true);
            if (isset($res['code'])){
                if ($res['code'] == 1) {
                    $restDays = $res['data']['dateWithWeekend'];
                } else {
                    $this->logText(array("type" => "workDay", "text" => "请求节假日接口失败：" . $res['warn']));
                }
            }
        } else {
            $this->logText(array("type" => self::page, "text" => "请求接口失败：请检查接口域名设置"));
        }

        $dt_start = strtotime("{$year}-01-01");
        $dt_end = strtotime("{$year}-12-31");
        while ($dt_start <= $dt_end) {
            $toDate = date('Y-m-d', $dt_start);

            if (isset($res['code']) && $res['code'] == 1) {
                if (!in_array($toDate, $restDays)) {
                    //走接口
                    $days[] = $toDate;
                }
            } else {
                //判断当前是否是周末
                if ((date('w', $dt_start) != 6) && (date('w', $dt_start) != 0)) {
                    //非周末
                    $days[] = date('Y-m-d', $dt_start);
                }
            }
            $dt_start = strtotime('+1 day', $dt_start);
        }
        update(array('table' => 'work_day', 'field' => array('workDay' => json_encode($days, 320)), 'where' => " id = '$id'"));
    }

    /*行政人事-工作日-辅助信息*/
    public function info()
    {
        //数据库查询
        $workDay = query("work_day", " id = '" . $this->get('id') . "' ");
        $workDayNum = count(json_decode($workDay['workDay'], true));
        //数组
        $trData = array(
            array(
                "ID：" => $workDay['id'],
                L('clock.table.tian_shu') . "：" => $workDayNum,
            ),
            array(
                L('clock.table.gxsj') . "：" => $workDay['updateTime'],
                L('clock.table.cjsj') . "：" => $workDay['time'],
            ),
        );
        $json['html'] = $this->tableEdit($trData);
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('clock.table.delWorkDay') . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /*行政人事-工作日-批量删除*/
    public function delete()
    {
        $array = $this->post('workDayId') ?? $this->post('id');
        if (!$this->power("workDay", "del")) {
            $json['warn'] = L('clock.table.zxbz');
        } elseif (empty($array)) {
            $json['warn'] = L('clock.table.nygsjdmzxzn');
        } else {
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                //查询
                $workDay = query("work_day", " id = '$id' ");
                //删除工作日
                delete(array("table" => "work_day", "where" => " id = '$id' "));
                //返回信息
                $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $workDay['name']], L('clock.table.del_workDay_text'));
                $this->logText(array("type" => "workDay", "text" => $text));
                $x++;
            }
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clock.table.del_workDay_warn'));
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        return json_encode($json, 320);
    }
}

